<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区 -->
        <el-card>
            <!-- 头部警告区域 -->
             <el-alert
             show-icon
                title="注意：只允许为第三级分类设置相关参数"
                type="warning"
                :closable="false"
                >
            </el-alert>
            <!-- 选中商品分类区 -->
            <el-row style="margin: 20px 0">
                <el-col>
                    <span>选中商品分类:&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <!-- 选择商品分类的级联选择框 -->
                     <el-cascader
                        v-model="selectedCateKeys"
                        :options="cateList"
                        expand-trigger="hover"
                        :props="cateProps"
                        @change="handleChange">
                      </el-cascader>
                </el-col>
            </el-row>

             <el-tabs v-model="activeName" @tab-click="handleTabsClick">
              <!-- 添加动态参数面板 -->
              <el-tab-pane label="动态参数" name="many">
                <el-button :disabled="isBtnDisabled" type="primary"  @click="addDialogVisible = true">添加参数</el-button>
                <el-table border stripe :data="manyTabData">
                   <el-table-column type="expand">
                      <template slot-scope="scope">
                        <!-- 循环渲染tag标签 -->
                        <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleCloseTag(index,scope.row)">
                          {{item}}
                        </el-tag>
                        <!-- 输入文本框 -->
                        <el-input
                          class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)"
                          style="width: 150px"
                        >
                        </el-input>
                        <!-- 添加按钮 -->
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ 添加</el-button>
                      </template>
                   </el-table-column>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                      <el-table-column label="操作">
                        <template slot-scope="scope">
                          <el-button type="primary" @click="editClick(scope.row)">编辑</el-button>
                          <el-button type="danger" @click="removeParams(scope.row)">删除</el-button>
                        </template>
                      </el-table-column>
                </el-table>
              </el-tab-pane>
               <!-- 添加动态参数面板 -->
              <el-tab-pane label="静态属性" name="only">
                <el-button   :disabled="isBtnDisabled" type="primary" @click="addDialogVisible = true">添加属性</el-button>
                 <el-table border stripe :data="onlyTabData">
                  <el-table-column type="expand">
                      <template slot-scope="scope">
                        <!-- 循环渲染tag标签 -->
                        <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleCloseTag(index,scope.row)">
                          {{item}}
                        </el-tag>
                        <!-- 输入文本框 -->
                        <el-input
                          class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)"
                          style="width: 150px"
                        >
                        </el-input>
                        <!-- 添加按钮 -->
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ 添加</el-button>
                      </template>
                   </el-table-column>
                    <el-table-column type="index"></el-table-column>
                    <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                      <el-table-column label="操作">
                        <template slot-scope="scope">
                          <el-button type="primary" @click="editClick(scope.row)">编辑</el-button>
                          <el-button type="danger" @click="removeParams(scope.row)">删除</el-button>
                        </template>
                      </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
            <!-- 添加弹窗 -->
            <el-dialog
              :title="'添加' + titleText"
              :visible.sync="addDialogVisible"
              width="50%"
              @click="closDialog"
              >
              <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
                <el-form-item :label="titleText" prop="attr_name">
                  <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams()">确 定</el-button>
              </span>
            </el-dialog>

             <!-- 编辑弹窗 -->
            <el-dialog
              :title="'修改' + titleText"
              :visible.sync="editDialogVisible"
              width="50%"
              @click="editClosDialog"
              >
              <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
                <el-form-item :label="titleText" prop="attr_name">
                  <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParams()">确 定</el-button>
              </span>
            </el-dialog>
        </el-card>
    </div>
</template>
<script>
export default {
  data () {
    return {
      cateList: [],
      // isBtnDisabled: false,
      selectedCateKeys: [],
      activeName: 'many',
      addDialogVisible: false,
      editDialogVisible: false,
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      manyTabData: [],
      onlyTabData: [],
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [{ required: true, message: '请添加参数', trigger: 'blur' }]
      },
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [{ required: true, message: '请添加参数', trigger: 'blur' }]
      }
    }
  },
  computed: {

    isBtnDisabled () {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    cateId () {
      if (this.selectedCateKeys.length === 3) {
        // this.cateId = this.selectedCateKeys[2]
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 对话框的名称
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取所有的商品分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status === 200) {
        this.cateList = res.data
      }
    },
    async handleChange () {
      // console.log(this.selectedCateKeys)
      this.getParamsList()
    },
    async getParamsList () {
      // 根据所选分类id和所属面板获取所属参数
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } })

      res.data.forEach(item => {
        // 做分割前先判断
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        console.log(item)
        // 控制文本框的显示与隐藏
        item.inputVisible = false
        item.inputValue = ''
      })

      if (res.meta.status === 200) {
        // console.log(res.data)
        if (this.activeName === 'many') {
          this.manyTabData = res.data
        } else {
          this.onlyTabData = res.data
        }
      }
    },
    // 点击编辑事件
    editClick (row) {
      this.editForm = JSON.parse(JSON.stringify(row))
      this.editDialogVisible = true
    },
    // tab页签的点击事件
    handleTabsClick () {
      this.getParamsList()
    },
    // 清楚对话框
    closDialog () {
      this.$refs.addFormRef.resetFields()
    },
    // 清空编辑对话框
    editClosDialog () {
      this.$refs.editFormRef.resetFields()
    },
    // 添加
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status === 201) {
          this.$message.success('添加成功')
        } else {
          this.$message.error(res.meta.msg)
        }
      })
      this.addDialogVisible = false
      this.getParamsList()
    },
    // 修改
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status === 200) {
          this.$message.success('修改成功')
        } else {
          this.$message.error(res.meta.msg)
        }
      })
      this.getParamsList()
      this.editDialogVisible = false
    },
    // 删除
    removeParams (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
        if (res.meta.status === 200) {
          this.$message.success('删除成功')
        } else {
          this.$message.error(res.meta.msg)
        }
        this.getParamsList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async saveAttrVals (row) {
      // 在push完毕后，需要发起网络参数
      const { data: res } = this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        // 使用，拼接
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success('修改参数项成功')
    },
    // 文本框失去焦点或按下按钮都会触发
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 如果return，则证明输入有内容给，需要做后续的处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      row.inputValue = ''
      this.saveAttrVals(row)
    },
    // 点击按钮显示文本输入框
    showInput (row) {
      console.log('showInput')
      console.log(row.inputVisible)
      row.inputVisible = true
      // 让文本框自动获取焦点
      // $nextTick函数作用：当页面中的上的元素被重新渲染之后，
      // 指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 处理标签的关闭,即移除参数可选项
    handleCloseTag (index, row) {
      // 将改tag从数组中移除
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    }
  }
}
</script>
<style scoped>
.el-row{
     margin-top: 25px;
}
.el-table {
  margin-top: 25px;
  font-size: 15px;
}
.el-card {
  margin-top: 25px;
  box-shadow: 0 1px 1px rgb(0, 0, 0, 0.15) !important;
}
.treeTable {
  margin-top: 20px;
}
.el-tag{
  margin: 5px;
}
</style>
